﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;

namespace OrderAggregator.InputFormats.Holiday
{
    /// <summary>
    /// Парсер заявок от Холидей (.csv формат)
    /// </summary>
    public class HolidayCsvFormat : BaseOrderFormat
    {
        public readonly static HolidayCsvFormat Instance = new HolidayCsvFormat();

        private HolidayCsvFormat()
        {
        }
       
        /// <summary>
        /// Parse
        /// </summary>
        /// <param name="filePath"></param>
        /// <param name="getStream"></param>
        /// <returns></returns>
        public override BaseOrder Parse(string filePath, Func<System.IO.Stream> getStream)
        {
            if (!string.Equals(System.IO.Path.GetExtension(filePath), dotCSV, StringComparison.InvariantCultureIgnoreCase))
            {
                return null;
            }

            var lines = ReadLines(filePath);

            return Parse(lines);
        }

        /// <summary>
        /// Parse
        /// </summary>
        /// <param name="lines"></param>
        /// <returns></returns>
        private BaseOrder Parse(string[] lines)
        {
            var order = new BaseOrder();

            int ordersStartLine = 0;
            var line = lines[0];


            const string Заказ_Number = "Заказ №";

            if (line.StartsWith(Заказ_Number))
            {
                var pos = line.IndexOf(" от");
                var str = line.Substring(Заказ_Number.Length, pos - Заказ_Number.Length).Trim();
                order.Id = str;

                str = line.Substring(pos + 3).Trim();
                //order.ReceiveTime = DateTime.ParseAndTranslate(str, RuCulture);

                ordersStartLine++;
            }

            const string Магазин = "Магазин:";

            line = lines[1];

            if (line.StartsWith(Магазин))
            {
                line = line.Replace("Компания Холидей ООО", "ООО \"Компания Холидей\"");

                line = line.Replace(", г. ", ", ");

                

                order.Client = line.Trim();

                ordersStartLine++;
            }

            const string Дата_поставки = "Дата поставки:";

            line = lines[2];

            if (line.StartsWith(Дата_поставки))
            {
                var str = line.Substring(Дата_поставки.Length).Trim();
                order.ReceiveTime = DateTime.Parse(str, RuCulture);

                ordersStartLine++;
            }
                       
            
            for (int lineIndex = ordersStartLine; lineIndex < lines.Length; lineIndex++)
            {
                string orderLine = lines[lineIndex];

                if (!string.IsNullOrEmpty(orderLine))
                {
                    var orderRow = ParseOrderRow(orderLine);
                    if (orderRow != null)
                    {
                        order.OrderRows.Add(orderRow);
                    }
                }
            }

            

            return order;
        }

        private static BaseOrderRow ParseOrderRow(string orderLine)
        {
            var words = orderLine.Split(';');

            var orderRow = new BaseOrderRow();
            orderRow.ProductCode = words[0].Trim();

            var str = words[1].Trim();
            if (str.StartsWith("\"") && str.EndsWith("\""))
            {
                str = str.Substring(1, str.Length - 2);
            }

            orderRow.ProductName = str;

            orderRow.Count = decimal.Parse(words[2], System.Globalization.CultureInfo.InvariantCulture);

            return orderRow;

        }
    }
}
